package com.yisu.expressway.api.core.service.impl;

import com.yisu.expressway.api.core.mapper.OrderMainMapper;
import com.yisu.expressway.api.core.mapper.OrderSubMapper;
import com.yisu.expressway.api.core.mapper.RefundRecordMapper;
import com.yisu.expressway.api.core.mapper.SpecificationGoodsMapper;
import com.yisu.expressway.api.core.service.IOrderService;
import com.yisu.expressway.api.domain.config.SystemConfig;
import com.yisu.expressway.api.domain.request.GoodsInfoRequest;
import com.yisu.expressway.api.domain.request.orderModule.ChangeOrderPaymentRequest;
import com.yisu.expressway.api.domain.request.orderModule.OrderListRequest;
import com.yisu.expressway.api.domain.request.orderModule.PaySuccessRequest;
import com.yisu.expressway.api.domain.vo.orderModule.OrderStatusNumVo;
import com.yisu.expressway.ewf.entity.OrderMain;
import com.yisu.expressway.ewf.entity.OrderSub;
import com.yisu.expressway.ewf.entity.RefundRecord;
import com.yisu.expressway.ewf.entity.SpecificationGoods;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by zj on 2017/5/4.
 */
@Service
public class OrderServiceImpl implements IOrderService {
    @Resource
    private OrderMainMapper orderMainMapper;
    @Resource
    private OrderSubMapper orderSubMapper;
    @Resource
    private SpecificationGoodsMapper specificationGoodsMapper;
    @Resource
    private RefundRecordMapper refundRecordMapper;
    @Resource
    private SystemConfig systemConfig;

    /**
     * 增加订单
     *
     * @param orderMain 订单主信息
     * @param orderSubs 子表信息
     * @return 成功，失败
     */
    @Override
    public long addOrder(OrderMain orderMain, List<OrderSub> orderSubs) {
        try {
            long currentDayMaxOrderId = orderMainMapper.getCurrentDayMaxOrderId();
            if (currentDayMaxOrderId == 0) {
                SimpleDateFormat sformat = new SimpleDateFormat("yyyyMMdd");
                currentDayMaxOrderId = Long.parseLong(sformat.format(new Date()) + "0000001");
            } else {
                currentDayMaxOrderId += 1;
            }
            orderMain.setOrderId(currentDayMaxOrderId);
            orderMainMapper.insert(orderMain);
            for (OrderSub item : orderSubs) {
                item.setOrderId(currentDayMaxOrderId);
                orderSubMapper.insert(item);
                GoodsInfoRequest goodsInfoRequest = new GoodsInfoRequest();
                goodsInfoRequest.setGoodsNo(item.getGoodsNo());
                goodsInfoRequest.setSpecificationNo(item.getSpecificationNo());
                goodsInfoRequest.setCategoryCode(String.valueOf(item.getCategoryCode()));
                goodsInfoRequest.setSubtractInventoryNum(item.getBuyNumber());
                specificationGoodsMapper.subtractInventoryNum(goodsInfoRequest);
            }
            return currentDayMaxOrderId;
        } catch (Exception ex) {
            return 0;
        }
    }

    /**
     * 通过规格编号，商品编号，分类编号获取规格商品信息
     *
     * @param goodsInfoRequest 请求信息
     * @return 成功，失败
     */
    @Override
    public SpecificationGoods getSpecificationGoods(GoodsInfoRequest goodsInfoRequest) {
        return specificationGoodsMapper.selectBySpecificationGoodsInfo(goodsInfoRequest);
    }

    /**
     * 通过订单编号，获取订单ID
     *
     * @param orderId 订单ID
     * @return
     */
    @Override
    public OrderMain getOrderMainByOrderId(Long orderId) {
        return orderMainMapper.selectByPrimaryKey(orderId);
    }

    /**
     * 更改订单支付方式
     *
     * @param changeOrderPaymentRequest 请求参数
     * @return
     */
    @Override
    public boolean changeOrderPayment(ChangeOrderPaymentRequest changeOrderPaymentRequest) {
        return orderMainMapper.changeOrderPayment(changeOrderPaymentRequest);
    }

    /**
     * 支付成功回调接口
     *
     * @param paySuccessRequest 支付成功回调参数
     * @return
     */
    @Override
    public boolean paySuccess(PaySuccessRequest paySuccessRequest) {
        if (orderMainMapper.paySuccess(paySuccessRequest)) {
            try {
                //添加销量不成功，不需要影响支付回调;
                List<OrderSub> orderSubList = orderSubMapper.getOrderSubListByOrderId(paySuccessRequest.getOrderId());
                if (!CollectionUtils.isEmpty(orderSubList)) {
                    for (OrderSub item : orderSubList) {
                        GoodsInfoRequest goodsInfoRequest = new GoodsInfoRequest();
                        goodsInfoRequest.setCategoryCode(String.valueOf(item.getCategoryCode()));
                        goodsInfoRequest.setGoodsNo(item.getGoodsNo());
                        goodsInfoRequest.setSpecificationNo(item.getSpecificationNo());
                        specificationGoodsMapper.addSalesVolume(goodsInfoRequest);
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return true;
        } else
            return false;
    }

    /**
     * 获取个人订单列表
     *
     * @param orderListRequest 个人订单列表请求参数
     * @return 订单列表
     */
    @Override
    public List<OrderMain> getUserOrderMainList(OrderListRequest orderListRequest) {
        return orderMainMapper.getUserOrderMainList(orderListRequest);
    }

    /**
     * 通过订单编号获取订单子表列表信息
     *
     * @param orderId 订单编号
     * @return 订单子表信息
     */
    @Override
    public List<OrderSub> getOrderSubListByOrderId(long orderId) {
        return orderSubMapper.getOrderSubListByOrderId(orderId);
    }

    /**
     * 通过用户帐号获取订单个各状态数量
     *
     * @param userAccount 用户帐号
     * @return 对象
     */
    @Override
    public OrderStatusNumVo getOrderStatusNumByUserAccount(@Param("userAccount") String userAccount) {
        return orderMainMapper.getOrderStatusNumByUserAccount(userAccount);
    }

    /**
     * 取消订单
     *
     * @param orderId 订单编号
     * @return 成功，失败
     */
    @Override
    public boolean cancelOrder(long orderId) {
        OrderMain updateModel = new OrderMain();
        try {
            OrderMain orderMain = orderMainMapper.selectByPrimaryKey(orderId);
            if (orderMain == null)
                return false;
            updateModel = new OrderMain();
            updateModel.setOrderId(orderId);
            updateModel.setCancelTime(new java.sql.Timestamp(new java.util.Date().getTime()));
            //如果订单已经支付，则进入退款流程；反之则直接取消订单
            if (orderMain.getOrderStatus() >= (OrderMain.OrderStatus.WAIT_DELIVER_GOODS.code)) {
                updateModel.setOrderStatus(OrderMain.OrderStatus.CANCEL_WAIT_PAY.code);
            } else {
                updateModel.setOrderStatus(OrderMain.OrderStatus.CANCEL_ORDER.code);
            }
            if (orderMainMapper.updateOrderStatus(updateModel) > 0) {
                if (updateModel.getOrderStatus().equals(OrderMain.OrderStatus.CANCEL_WAIT_PAY.code)) {
                    //追加退款流水
                    RefundRecord refundRecord = new RefundRecord();
                    refundRecord.setStatus(RefundRecord.StatusEnum.WAIT_REFUND.code);
                    refundRecord.setOrderId(orderId);
                    refundRecord.setRefundAmount(orderMain.getOrderAmount());
                    refundRecord.setCreateBy("sys");
                    refundRecordMapper.insert(refundRecord);
                }
                addInventoryNum(orderId);
            } else {
                return false;
            }
        } catch (Exception ex) {
            return false;
        }
        return true;
    }

    private void addInventoryNum(Long orderId) {
        List<OrderSub> orderSubList = orderSubMapper.getOrderSubListByOrderId(orderId);
        if (!CollectionUtils.isEmpty(orderSubList)) {
            for (OrderSub item : orderSubList) {
                GoodsInfoRequest goodsInfoRequest = new GoodsInfoRequest();
                goodsInfoRequest.setGoodsNo(item.getGoodsNo());
                goodsInfoRequest.setSpecificationNo(item.getSpecificationNo());
                goodsInfoRequest.setCategoryCode(String.valueOf(item.getCategoryCode()));
                goodsInfoRequest.setSubtractInventoryNum(item.getBuyNumber());
                specificationGoodsMapper.addInventoryNum(goodsInfoRequest);
            }
        }
    }

    /**
     * 更改订单状态
     *
     * @param orderMain 订单详情
     * @return
     */
    @Override
    public boolean updateOrderUpdate(OrderMain orderMain) {
        return orderMainMapper.updateOrderStatus(orderMain) > 0;
    }

    /**
     * 通过主键获取退款流水信息
     *
     * @param primaryKey
     * @return
     */
    @Override
    public RefundRecord getRefundRecordByPrimaryKey(Long primaryKey) {
        return refundRecordMapper.selectByPrimaryKey(primaryKey);
    }

    /**
     * 修改退款信息
     *
     * @param updateModel
     * @return
     */
    @Override
    public boolean updateRefundRecord(RefundRecord updateModel) {
        return refundRecordMapper.updateByPrimaryKeySelective(updateModel) > 0;
    }

    /**
     * 退款成功
     *
     * @param updateModel 退款更新信息
     * @return 成功，失败
     */
    @Override
    public boolean refundSuccess(RefundRecord updateModel) {
        try {
            if (refundRecordMapper.updateByPrimaryKeySelective(updateModel) > 0) {
                OrderMain updateOrderMain = new OrderMain();
                updateOrderMain.setOrderId(updateModel.getOrderId());
                updateOrderMain.setOrderStatus(OrderMain.OrderStatus.CANCEL_ORDER.code);
                orderMainMapper.updateOrderStatus(updateOrderMain);
            }
        } catch (Exception ex) {
            return false;
        }

        return true;
    }

    /**
     * 通过订单号取消订单
     *
     * @return
     */
    @Override
    public boolean cancelOrderForJob() {
        int cancelTimeLimit = systemConfig.getOrderCancelTimeLimit();
        if (cancelTimeLimit <= 0)
            cancelTimeLimit = 30;
        List<OrderMain> orderMains = orderMainMapper.cancelOrderList(cancelTimeLimit);
        if (orderMains.size() > 0) {
            for (OrderMain orderMain : orderMains) {
                orderMain.setOrderStatus(-100);
                orderMainMapper.updateOrderStatus(orderMain);
                try {
                    addInventoryNum(orderMain.getOrderId());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return true;
    }

    /**
     * 确认收货
     */
    @Override
    public void confirmOrder() {
        int confirmOrderDays = systemConfig.getConfirmOrderDays();
        if (confirmOrderDays <= 0)
            confirmOrderDays = 15;

        orderMainMapper.confirmOrder(confirmOrderDays);
    }
}
